# -*- coding: utf-8 -*-
# -- coding: utf-8 --
""" 
deprecated
"""

import uuid
from requests import RequestException
import inspect
import hprose
import unittest
import sys
import os
import time

# 添加执行环境
file_exec_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
sys.path.insert(0, file_exec_path)

from framework_strategy.gopy.trader.engine import EmailEngine, MainEngine, EventEngine  # NOQA
from framework_strategy.gopy.base.api import API, Event  # NOQA
from framework_strategy.gopy.gateways.object import *  # NOQA
from framework_strategy.gopy.gateways.xt.xt_api import XTGateway  # NOQA
from framework_strategy.gopy.gateways.object import *  # NOQA
from framework_strategy.gopy.gateways.binance.binance_api import BINANCEGateway  # NOQA
from framework_strategy.gopy.gateways.hprose import HproseClient  # NOQA


class HproseTest(unittest.TestCase):

    @unittest.skip
    def test_init(self):
        mkd = MarketKlineData
        print(mkd.__annotations__)
        pass

    @unittest.skip
    def test_get_server(self):
        """  """
        event_engine = EventEngine()
        main_engine = MainEngine(event_engine)
        main_engine.add_gateway(XTGateway)
        hpc = HproseClient(main_engine, event_engine)
        # hpc.start_server()

    @unittest.skip
    def test_get_describe(self):
        event_engine = EventEngine()
        main_engine = MainEngine(event_engine)
        main_engine.add_gateway(XTGateway)
        main_engine.add_gateway(BINANCEGateway)

        hpc = HproseClient(main_engine, event_engine)

        print(hpc.describe())
        event_engine.stop()
        pass


"""
测试用例

"""


def func(data):

    print("--callback--", data)
    pass


class MyFilter(object):
    def inputFilter(self, data, context):
        print("[inputFilter]", data, self, context)
        return data

    def outputFilter(self, data, context):
        # print("[outputFilter]", data, self, context)
        return data


def main():
    client = hprose.HttpClient('http://127.0.0.1:8888/')
    client.filter = MyFilter()

    # print(dir(client))
    print(client.send_data(
        {"Mon": 1, "Tue": 2, "Wed": {"i1": "Wed", "i2": 5}}, func))


class ApiFilter(object):

    def inputFilter(self, data, context):
        # print("[inputFilter]", data, self, context)
        return data

    def outputFilter(self, data, context):
        # print("[outputFilter]", data, self, context)
        return data


def describe():

    # pip3 install hprose -i https://pypi.douban.com/simple
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    print(client.describe())


def server_time():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    print(client.get_server_time({"xt": {}}))


def get_account_info():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    print(client.get_account_info())


error1 = (ValueError, AttributeError)
error2 = (RecursionError, RequestException)

try:
    pass
except error1 as e:
    pass
except error2 as e:
    pass
finally:
    pass


def get_all_market_config():
    # pip3 install hprose -i https://pypi.douban.com/simple
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    print(client.get_all_market_config({
        "XT":{},
        # "FTX": {},
        # 'BINANCE': {}
        }))


def get_market_kline_data():
    print("---------------")
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_market_kline_data({
        "xt": [
        {"market": "btc_usdt", "type": "1min", "since": int(time.time())},
        ],
        'ftx': [
            {'market': 'btc_usdt', 'type': 60}
        ],
        'binance': [
            {'market': 'btc_usdt', 'type': '1m'}
        ]
    }))
    print("-----", time.time() - nt)


def get_market_trade_data():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_market_trades({
        # "xt": {"market": "btc_usdt"},
        # 'binance': {'market': 'btc_usdt'},
        'ftx': {'market': 'btc_usdt'},
    }))
    print("-----", time.time() - nt)


def get_market_ticker_data():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_market_ticker_data({
        # "xt": {"market": "btc_usdt"},
        'binance': {'market': 'btc_usdt'},
        'ftx': {'market': 'btc_usdt'},
    }))
    print("-----", time.time() - nt)


def get_market_tickers_data():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_market_tickers_data({
        # 'xt': {},
        'binance': {},
        'ftx': {},
    }))
    print("-----", time.time() - nt)


def get_market_depth_data():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()  # [exchange]:[market]:depth
    print(client.get_market_depth_data({
        # "xt": [
        #     {"market": "btc_usdt"},
        #     {"market": "eth_usdt"}
        # ],
        # 'ftx': [{'market': 'btc_usdt'}],
        'binance': [{'market': 'btc_usdt'}],
    }))
    print("-----", time.time() - nt)


def get_account_balance():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_account_balance({
            "xt": {
                "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
                "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"
            },
            'ftx': {
                'accesskey': '4HBl4ZV5lzqZeNF-ruhpD8DbajdmewZ0AhegNmGM',
                'secretkey': 'Uz6MtIAd4ruIfI2yr5Ms0GPV54xsL7oKdG6mCyf4'
            },
            'binance': {
                'accesskey': 'XXNxw5YhKRqxqtm6Arw9Q7cnukMrO0QtBE6oUHzozsnIBKljnerp1laAAl6KtUwu',
                'secretkey': 'gWt9AgrhiueWaHNYnF42sx4emuROU6ct55Y2RqHYRUVsVRNTz6A5Z63d6bFVuoTS'
            }
            })
        )
    print("-----", time.time() - nt)


def get_account_fund():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.get_account_fund({"xt": {
        "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
        "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"}}))
    print("-----", time.time() - nt)


def handle():
    print("-----------")


def get_uuid():
    get_timestamp_uuid = uuid.uuid1()  # 根据 时间戳生成 uuid , 保证全球唯一
    print("len---- ", len(str(get_timestamp_uuid.int)))
    return get_timestamp_uuid.int


def send_order():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()
    print(client.send_order({
        # "xt": {
        #     "market": "btc_usdt",
        #     "price": 100,
        #     "app_name": "test",
        #     "user_name": "zhangsan",
        #     "note": "老王到此一游",
        #     "type": 1,
        #     "entrustType": "0",
        #     "number": 10,
        #     "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
        #     "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
        "xtfuture": {
            "app_name": "test",
            "user_name": "zhangsan",
            "note": "---",
            'accesskey': 'b1000aa0-9119-4ce7-a963-e7a0fe0055cb',
            'secretkey': 'b9992066608e6b84b531cbf1bf36b06e9a79add8',
            'market': "dot_usdt",
            'price': 8.86,
            'amount': 100,
            'order_side': "BUY",
            'order_type': "LIMIT",
            'position_side': "LONG",
        },
        "uuid": get_uuid()
        }))
    print("-----", time.time() - nt)


def send_orders():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    order = [
        {"price": "19000", "amount": "0.001", "type": 0, "market": "btc_usdt", },
        {"price": "19001", "amount": "0.001", "type": 0, "market": "btc_usdt", },
        {"price": "500", "amount": "0.01", "type": 1, "market": "eth_usdt", },
        {"price": "555", "amount": "0.01", "type": 1, "market": "eth_usdt", },
    ]

    print(client.send_orders({
        "xt": {
            "data": order,
            "app_name": "test",
            "user_name": "zhangsan",
            "note": "老王到此一游",
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
        "uuid": get_uuid(),
    }))
    print("-----", time.time() - nt)


def cancel_order():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    order = [
        {"id": 6952079642737782784, "market": "btc_usdt"},
        {"id": 6952079642737782784, "market": "btc_usdt"},
        {"id": 6952079643610198016, "market": "eth_usdt"},
        {"id": 6952079643610198016, "market": "eth_usdt"},
    ]

    print(client.cancel_order({
        "xt": {
            "data": order,
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
        "uuid": get_uuid(),
    }))
    print("-----", time.time() - nt)


def cancel_orders():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    order = [
        {
            "market": "btc_usdt",
            "data": [
                "6952080370847985664",
                "6952080370847985665",
            ]
        },
        {
            "market": "eth_usdt",
            "data": [
                "6952080371581988864",
                "6952080371581988865",
            ]
        },
    ]

    print(client.cancel_orders({
        "xt": {
            "data": order,
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
        "uuid": get_uuid(),
    },
    ))
    print("-----", time.time() - nt)


def get_account_order():

    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    order = [
        {
            "market": "btc_usdt",
            "data": [
                "6952080370847985664",
                "6952080370847985665",
            ]
        },
        {
            "market": "eth_usdt",
            "data": [
                "6952080371581988864",
                "6952080371581988865",
            ]
        },
    ]

    print(client.get_account_order({
        "xt": {
            "data": order,
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
    },
    ))
    print("-----", time.time() - nt)


def get_open_order():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    print(client.get_open_order({
        "xt": {
            "market": ["btc_usdt", "eth_usdt"],
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
        'binance': {'market': ['btc_usdt']},
        'ftx': {'market': ['btc_usdt']},
    },
    ))
    print("-----", time.time() - nt)


def get_orders():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    order = [
        {
            "market": "btc_usdt",
            "data": [
                "6952080370847985664",
                "6952080370847985665",
            ]
        },
        {
            "market": "eth_usdt",
            "data": [
                "6952080371581988864",
                "6952080371581988865",
            ]
        },
    ]

    print(client.get_orders({
        "xt": {
            "data": order,
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
    },
    ))
    print("-----", time.time() - nt)


def get_mine_orders():
    client = hprose.HttpClient('http://127.0.0.1:9898/')
    client.filter = ApiFilter()
    nt = time.time()

    print(client.get_mine_orders({
        "xt": {
            "market": ["btc_usdt", "eth_usdt"],
            "accesskey": "c15c7459-b65a-43af-8165-7ac0ae853154",
            "secretkey": "939a9ccc101f4df7075a1d0cdc2d3f79e88b00bd"},
    },
    ))
    print("-----", time.time() - nt)

import requests

def request_baidu():
    res = requests.get("http://www.baidu.com")
    print(res)


if __name__ == "__main__":
    # unittest.main()
    import threading
    import multiprocessing
    # count = 0
    # task = []

    # for _ in range(100):
    #     task.append(multiprocessing.Process(target=get_all_market_config, daemon=True))

    # for t in task:
    #     count +=1
    #     print("-------------------------", count)
    #     t.start()

    # time.sleep(200)
    # describe()
    # server_time()
    
    # nt = time.time()
    # import multiprocessing
    # count = 0
    # task = []

    # for _ in range(50):
    #     task.append(multiprocessing.Process(target=get_all_market_config, daemon=True))

    # for t in task:
    #     count +=1
    #     print("-------------------------", count)
    #     t.start()

    # time.sleep(200)

    # get_all_market_config()
    # # print(1, "*"* 20)
    # get_market_kline_data()
    # print(2, "*"* 20)
    # get_market_ticker_data()
    # print(2, "*"* 20)
    # get_market_trade_data()
    # # print(2, "*"* 20)
    # get_market_tickers_data()
    # # print(3, "*"* 20)
    # get_market_depth_data()
    # # print(4, "*"* 20)
    # get_account_balance()
    # print(5, "*"* 20)
    # get_open_order()
    # # print(6, "*"* 20)
    send_order()

    # print("[time] ", time.time() - nt)
